<template>
  <n-modal v-model:show="visible" preset="dialog" title="批量导入干部信息" style="width: 600px;">
    <div class="import-dialog">
      <n-alert type="info" class="mb-4">
        <template #header>导入说明</template>
        <div class="text-sm">
          <p>1. 请使用标准的Excel模板格式，表头必须包含：姓名、性别、出生年月、所属单位、拟授课方向、意向高校1</p>
          <p>2. 所属单位名称必须在系统中存在</p>
          <p>3. 必填字段不能为空</p>
          <p>4. 支持.xlsx和.xls格式文件，文件大小不超过10MB</p>
        </div>
      </n-alert>

      <div v-if="!selectedFile && !importResult" class="upload-area">
        <n-upload
          ref="uploadRef"
          :max="1"
          :show-file-list="false"
          accept=".xlsx,.xls"
          @change="handleFileChange"
        >
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <n-icon size="48" :depth="3">
                <CloudUploadOutline />
              </n-icon>
            </div>
            <n-text style="font-size: 16px;">
              点击或者拖动文件到该区域
            </n-text>
            <n-p depth="3" style="margin: 8px 0 0 0;">
              选择文件后，需要点击"确认导入"按钮才会开始上传
            </n-p>
          </n-upload-dragger>
        </n-upload>
      </div>

      <div v-if="selectedFile && !isProcessing && !importResult" class="preview-area">
        <n-card>
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <n-icon size="24" class="mr-3 text-green-500">
                <CheckmarkCircleOutline />
              </n-icon>
              <div>
                <n-text class="font-bold">{{ selectedFile.name }}</n-text>
                <n-p depth="3" style="margin: 0; font-size: 12px;">
                  文件已就绪，请点击右下角的“确认导入”按钮开始处理。
                </n-p>
              </div>
            </div>
            <n-button @click="handleRemoveFile" quaternary circle>
              <template #icon>
                <n-icon><CloseOutline /></n-icon>
              </template>
            </n-button>
          </div>
        </n-card>
      </div>

      <div v-if="isProcessing" class="uploading-area">
        <div class="flex flex-col items-center justify-center py-12">
          <n-spin size="large" />
          <n-text class="mt-4" style="font-size: 16px;">正在导入数据...</n-text>
          <n-p depth="3" style="margin: 8px 0 0 0;">
            请稍候，这可能需要一点时间...
          </n-p>
        </div>
      </div>

      <div v-if="importResult" class="import-result">
        <n-result
          :status="importResult.failed === 0 ? 'success' : 'warning'"
          :title="importResult.failed === 0 ? '全部导入成功' : '部分导入成功'"
        >
          <template #footer>
            <div class="result-stats">
              <n-statistic label="总计" :value="importResult.total" />
              <n-statistic label="成功" :value="importResult.success" />
              <n-statistic label="失败" :value="importResult.failed" />
            </div>
          </template>
        </n-result>
        <div v-if="importResult.errors && importResult.errors.length > 0" class="mt-4">
          <n-card title="失败数据详情" size="small">
            <n-data-table
              :columns="errorColumns"
              :data="importResult.errors"
              :pagination="{ pageSize: 5 }"
              :max-height="300"
              size="small"
            />
          </n-card>
        </div>
      </div>
    </div>

    <template #action>
      <div class="flex justify-between w-full">
        <div>
          <n-button v-if="!selectedFile && !importResult" @click="downloadTemplate" type="info" ghost>
            下载模板
          </n-button>
        </div>
        <div>
          <n-button @click="handleCancel" :disabled="isProcessing">
            {{ importResult ? '关闭' : '取消' }}
          </n-button>
          <n-button
            v-if="selectedFile && !importResult"
            type="primary"
            @click="handleConfirmImport"
            :loading="isProcessing"
            :disabled="isProcessing"
            class="ml-3"
          >
            确认导入
          </n-button>
        </div>
      </div>
    </template>
  </n-modal>
</template>

<script setup>
import { ref, watch } from 'vue';
import {
  NModal, NAlert, NUpload, NUploadDragger, NIcon, NText, NP, NButton,
  NResult, NStatistic, NSpin, NDataTable, NCard, useMessage
} from 'naive-ui';
import { CloudUploadOutline, CheckmarkCircleOutline, CloseOutline } from '@vicons/ionicons5';
import axios from 'axios';

const message = useMessage();

const props = defineProps({
  show: { type: Boolean, default: false }
});

const emit = defineEmits(['update:show', 'success']);

const visible = ref(false);
const uploadRef = ref(null);
const isProcessing = ref(false);
const importResult = ref(null);
const selectedFile = ref(null); // **核心改动**: 用于存储用户选择的文件对象

// 错误数据表格列定义
const errorColumns = [
  { title: '行号', key: 'row', width: 60 },
  { title: '姓名', key: 'name', width: 100 },
  { title: '错误信息', key: 'error', width: 300 }
];

// 监听props.show来控制模态框显示
watch(() => props.show, (newVal) => {
  visible.value = newVal;
  if (newVal) {
    // 每次打开时，重置所有状态
    isProcessing.value = false;
    importResult.value = null;
    selectedFile.value = null;
    uploadRef.value?.clear(); // 清空上传组件的内部文件列表
  }
});

watch(visible, (newVal) => {
  emit('update:show', newVal);
});

// **步骤1: 用户选择文件后的处理**
const handleFileChange = (data) => {
  if (data.fileList.length > 0) {
    const fileInfo = data.fileList[0];
    const rawFile = fileInfo.file;

    if (!rawFile) return;

    // 前端校验
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel'
    ];
    if (!allowedTypes.includes(rawFile.type)) {
      message.error('只支持Excel文件格式(.xlsx, .xls)');
      uploadRef.value?.clear();
      return;
    }
    if (rawFile.size > 10 * 1024 * 1024) {
      message.error('文件大小不能超过10MB');
      uploadRef.value?.clear();
      return;
    }

    // 校验通过，将文件对象存起来
    selectedFile.value = rawFile;
  }
};

// **(可选) 用户移除已选择的文件**
const handleRemoveFile = () => {
  selectedFile.value = null;
  uploadRef.value?.clear();
};

// **步骤2: 用户点击“确认导入”按钮后执行**
const handleConfirmImport = async () => {
  if (!selectedFile.value) {
    message.error('请先选择一个文件');
    return;
  }

  isProcessing.value = true;
  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);

    const response = await axios.post('http://localhost:3001/api/cadres/import', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    importResult.value = response.data.data;

    if (importResult.value.failed === 0) {
      message.success(`成功导入 ${importResult.value.success} 条干部信息！`);
    } else {
      message.warning(`导入完成，成功 ${importResult.value.success} 条，失败 ${importResult.value.failed} 条。`);
    }

    if (importResult.value.success > 0) {
      emit('success');
    }
  } catch (error) {
    console.error('导入文件失败:', error);
    const errorMessage = error.response?.data?.error || '导入失败，请检查文件内容或联系管理员';
    message.error(errorMessage);
    // 失败后允许用户重新操作
    selectedFile.value = null;
    uploadRef.value?.clear();
  } finally {
    isProcessing.value = false;
  }
};

// 下载模板
const downloadTemplate = () => {
  const templateUrl = 'http://localhost:3001/api/export/cadres';
  window.open(templateUrl, '_blank');
  message.info('正在下载模板文件...');
};

// 取消/关闭
const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped>
.import-dialog {
  padding: 16px 0;
}
.upload-area, .preview-area, .uploading-area {
  margin: 16px 0;
}
.result-stats {
  display: flex;
  gap: 24px;
  justify-content: center;
  margin: 16px 0;
}
</style>